<template>
  <div class="module-card">
    <div class="module-header">
      <h3>成员管理</h3>
      <button @click="showAddMemberDialog = true" class="btn-primary">添加成员</button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-group">
        <input 
          v-model="searchForm.keyword" 
          placeholder="请输入姓名或学号" 
          class="search-input"
          @keyup.enter="handleSearch"
        >
        <button @click="handleSearch" class="btn-search">搜索</button>
        <button @click="resetSearch" class="btn-reset">重置</button>
      </div>
    </div>

    <table class="data-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>学号</th>
          <th>部门</th>
          <th>职位</th>
          <th>入社时间</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(member, index) in displayedMembers" :key="member.id">
          <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
          <td>{{ member.username }}</td>
          <td>{{ member.studentId }}</td>
          <td>{{ getDepartmentName(member.departmentId) }}</td>
          <td>{{ member.position }}</td>
          <td>{{ formatJoinTime(member.joinTime) }}</td>
          <td>{{ member.status === 'active' ? '正常' : '禁用' }}</td>
          <td class="operation-buttons">
            <button @click="handleChangeStatus(member)" class="btn-status">
              {{ member.status === 'active' ? '禁用' : '启用' }}
            </button>
            <button @click="handleDeleteMember(member.id)" class="btn-delete">删除</button>
            <button @click="navigateToDetail(member.id)" class="btn-view">详情</button>
          </td>
        </tr>
        <tr v-if="members.length === 0">
          <td colspan="8" class="no-data">暂无成员数据</td>
        </tr>
      </tbody>
    </table>
    <!-- 分页组件 -->
    <div class="pagination-container" v-if="totalPages > 1">
      <div class="pagination-info">
        共 {{ totalMembers }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
      </div>
      <div class="pagination">
        <button 
          @click="goToPage(1)" 
          :disabled="currentPage === 1"
          class="pagination-btn"
        >
          首页
        </button>
        <button 
          @click="goToPage(currentPage - 1)" 
          :disabled="currentPage === 1"
          class="pagination-btn"
        >
          上一页
        </button>
        <button 
          v-for="page in pageNumbers" 
          :key="page"
          @click="goToPage(page)"
          :class="['pagination-btn', { active: currentPage === page }]"
        >
          {{ page }}
        </button>
        <button 
          @click="goToPage(currentPage + 1)" 
          :disabled="currentPage === totalPages"
          class="pagination-btn"
        >
          下一页
        </button>
        <button 
          @click="goToPage(totalPages)" 
          :disabled="currentPage === totalPages"
          class="pagination-btn"
        >
          末页
        </button>
      </div>
    </div>
    <!-- 添加成员弹窗 -->
    <div v-if="showAddMemberDialog" class="dialog-overlay">
      <div class="dialog">
        <div class="dialog-header">
          <h3>添加成员</h3>
          <button @click="closeMemberDialog" class="dialog-close">&times;</button>
        </div>
        <div class="dialog-content">
          <div class="form-group">
            <label>姓名：</label>
            <input v-model="memberForm.username" required>
          </div>
          <div class="form-group">
            <label>学院：</label>
            <input v-model="memberForm.college" required>
          </div>
          <div class="form-group">
            <label>学号：</label>
            <input v-model="memberForm.studentId" required>
          </div>
          <div class="form-group">
            <label>联系电话：</label>
            <input v-model="memberForm.phone" required>
          </div>
          <div class="form-group">
            <label>部门：</label>
            <select v-model="memberForm.departmentId" required>
              <option v-for="(name, id) in departmentMap" :key="id" :value="id">{{ name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>职位：</label>
            <select v-model="memberForm.position" required>
              <option value="部长">部长</option>
              <option value="副部长">副部长</option>
              <option value="部员">部员</option>
            </select>
          </div>
          <div class="form-group">
            <label>入社年份：</label>
            <input v-model="memberForm.joinTime" type="number" min="2000" max="2099" required>
          </div>
          <div class="form-group">
            <label>备注：</label>
            <textarea v-model="memberForm.note" rows="3"></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="saveMember" class="btn-primary">添加</button>
          <button @click="closeMemberDialog" class="btn-secondary">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const members = ref([])
const showAddMemberDialog = ref(false)
const editingMember = ref(null)

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(5)
const totalMembers = ref(0)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

const memberForm = reactive({
  username: '',
  college: '',
  studentId: '',
  phone: '',
  departmentId: 2,
  position: '部员',
  joinTime: new Date().getFullYear(),
  status: 'active',
  note: ''
})

// 部门映射表
const departmentMap = {
  1: '采播部',
  2: '电台部',
  3: '主持部',
  4: '新媒体部',
  5: '技术部',
  6: '办公室',
  7: '运营部',
  8: '摄影部',
  9: '网宣部'
}
// 计算属性：当前页显示的成员
const displayedMembers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return members.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalMembers.value / pageSize.value)
})

// 计算显示的页码
const pageNumbers = computed(() => {
  const pages = []
  const maxVisiblePages = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2))
  let endPage = startPage + maxVisiblePages - 1
  
  if (endPage > totalPages.value) {
    endPage = totalPages.value
    startPage = Math.max(1, endPage - maxVisiblePages + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})
// 获取部门名称
const getDepartmentName = (deptId) => {
  return departmentMap[deptId] || '未知部门'
}

// 格式化入社时间
const formatJoinTime = (time) => {
  if (!time) return '未填写'
  if (typeof time === 'string' && time.includes('-')) {
    return time.split('T')[0] // 处理日期字符串
  }
  return time
}

// 获取成员列表
const fetchMembers = async () => {
  try {
    const response = await fetch('http://localhost:8080/user/department/2', {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
    const result = await response.json()
    
    if (result.code === 200) {
      members.value = result.data.map(member => ({
        ...member,
        joinTime: member.join_time || member.joinTime // 兼容不同字段名
      }))
      // 关键：更新总成员数
      totalMembers.value = members.value.length
    } else {
      throw new Error(result.message || '获取成员列表失败')
    }
  } catch (error) {
    console.error('获取成员列表失败:', error)
    alert('获取成员列表失败，请稍后重试')
  }
}
// 搜索功能
const handleSearch = () => {
  if (!searchForm.keyword.trim()) {
    // 如果搜索关键词为空，显示所有成员
    fetchMembers()// 重置时会通过fetchMembers更新totalMembers
    return
  }
  
  // 过滤成员数据
  const filteredMembers = members.value.filter(member => 
    member.username.includes(searchForm.keyword.trim()) || 
    member.studentId.includes(searchForm.keyword.trim())
  )
  
  members.value = filteredMembers
  totalMembers.value = filteredMembers.length
  currentPage.value = 1 // 重置到第一页
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  fetchMembers()
}

// 分页功能
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}
// 保存成员
const saveMember = async () => {
  try {
    // 检查必填字段
    if (!memberForm.username || !memberForm.studentId || !memberForm.college || 
        !memberForm.phone || !memberForm.departmentId || !memberForm.position) {
      alert('请填写所有必填字段');
      return;
    }

    // 准备用户数据
    const userData = {
      username: memberForm.username,
      password: memberForm.studentId, // 默认密码设为学号
      studentId: memberForm.studentId,
      role: 'member',
      departmentId: memberForm.departmentId,
      position: memberForm.position,
      joinTime: memberForm.joinTime,
      status: memberForm.status
    }

    // 准备用户信息数据
    const userInfoData = {
      college: memberForm.college,
      phone: memberForm.phone,
      note: memberForm.note
    }

    // 1. 创建用户
    const userRes = await fetch('http://localhost:8080/user/add', {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(userData)
    })

    const userResult = await userRes.json()
    
    if (userResult.code === 200) {
      // 确保获取到用户ID
      const userId = userResult.data?.id || userResult.data?.userId
      if (!userId) {
        console.error('用户创建成功但未返回用户ID:', userResult)
        alert('用户创建成功，但服务器未返回用户ID')
        return
      }
      
      // 2. 创建用户信息
      const infoRes = await fetch('http://localhost:8080/userInfo/add', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          userId: userId,  // 使用获取到的用户ID
          college: memberForm.college,
          phone: memberForm.phone,
          honor: memberForm.honor || '无',
          note: memberForm.note
        })
      })

      const infoResult = await infoRes.json()
      
      if (infoResult.code === 200) {
        alert('成员添加成功')
        closeMemberDialog()
        fetchMembers()
      } else {
        // 用户信息创建失败，删除已创建的用户
        await fetch(`http://localhost:8080/user/${userId}`, {
          method: 'DELETE'
        })
        alert(infoResult.message || '添加用户信息失败，已撤销用户创建')
      }
    } else {
      alert(userResult.message || '添加用户失败')
    }
  } catch (error) {
    console.error('添加成员失败:', error)
    alert('添加失败，请检查网络连接或联系管理员')
  }
}

// 关闭弹窗
const closeMemberDialog = () => {
  showAddMemberDialog.value = false
  Object.assign(memberForm, {
    username: '',
    college: '',
    studentId: '',
    phone: '',
    departmentId: 2,
    position: '部员',
    joinTime: new Date().getFullYear(),
    status: 'active',
    note: ''
  })
}

// 更改成员状态
const handleChangeStatus = async (member) => {
  try {
    const newStatus = member.status === 'active' ? 'inactive' : 'active'
    const response = await fetch(`http://localhost:8080/user/status/${member.id}/${newStatus}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
    
    const result = await response.json()
    if (result.code === 200) {
      member.status = newStatus
    } else {
      alert(result.message || '操作失败')
    }
  } catch (error) {
    console.error('更改成员状态失败:', error)
    alert('操作失败，请重试')
  }
}

// 删除成员
const handleDeleteMember = async (id) => {
  if (!confirm('确定要删除该成员吗？')) return
  
  try {
    // 先设置为非活跃状态
    const statusResponse = await fetch(`http://localhost:8080/user/status/${id}/inactive`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
    
    const statusResult = await statusResponse.json()
    if (statusResult.code === 200) {
      // 然后删除用户
      const deleteResponse = await fetch(`http://localhost:8080/user/${id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      })
      
      const deleteResult = await deleteResponse.json()
      if (deleteResult.code === 200) {
        fetchMembers()
      } else {
        alert(deleteResult.message || '删除失败')
      }
    } else {
      alert(statusResult.message || '操作失败')
    }
  } catch (error) {
    console.error('删除成员失败:', error)
    alert('删除失败，请重试')
  }
}

// 导航到详情页
const navigateToDetail = (id) => {
  router.push(`/buzhang/diantai/memberDetail/${id}`)
}

onMounted(() => {
  fetchMembers()
})
</script>

<style scoped> 
/* 模块容器样式 */
.module-card {
  font-size: 16px;
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  width: 100%;
  max-width: 1400px;
  margin: 20px auto;
}

/* 模块头部样式 */
.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.module-header h3 {
  margin: 0;
  font-size: 22px;
  color: #1f2329;
  font-weight: 600;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 24px;
}

.search-group {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  padding: 10px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  width: 320px;
  height: 42px;
  font-size: 15px;
  transition: all 0.3s;
}

.search-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 按钮基础样式 */
.btn-primary, .btn-search, .btn-reset, 
.btn-status, .btn-delete, .btn-view, 
.btn-secondary, .pagination-btn {
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 15px;
  height: 42px;
  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 主要按钮样式 */
.btn-primary, .btn-search {
  background-color: #1890ff;
  color: white;
  border: none;
}

.btn-primary:hover, .btn-search:hover {
  background-color: #40a9ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

/* 次要按钮样式 */
.btn-reset, .btn-secondary {
  background-color: #fff;
  border: 1px solid #d9d9d9;
  color: rgba(0, 0, 0, 0.65);
}

.btn-reset:hover, .btn-secondary:hover {
  color: #1890ff;
  border-color: #1890ff;
  background-color: #f0f7ff;
  transform: translateY(-2px);
}

/* 表格样式 */
.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  font-size: 15px;
  table-layout: auto;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.data-table th,
.data-table td {
  padding: 12px 16px;
  text-align: center;
  border-bottom: 1px solid #f5f5f5;
  white-space: normal;
  word-wrap: break-word;
  vertical-align: middle;
}

/* 表头样式 */
.data-table th {
  background-color: #fafafa;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  position: sticky;
  top: 0;
  z-index: 10;
  white-space: nowrap;
  font-size: 15px;
}

.data-table tr:hover td {
  background-color: #f9f9f9;
}

/* 列宽调整 */
.data-table th:nth-child(1),
.data-table td:nth-child(1) {
  width: 60px;
}

.data-table th:nth-child(7),
.data-table td:nth-child(7) {
  width: 90px;
}

.data-table th:nth-child(8),
.data-table td:nth-child(8) {
  min-width: 240px;
}

.data-table th:nth-child(2),
.data-table td:nth-child(2),
.data-table th:nth-child(3),
.data-table td:nth-child(3) {
  min-width: 120px;
}

.data-table th:nth-child(4),
.data-table td:nth-child(4),
.data-table th:nth-child(5),
.data-table td:nth-child(5) {
  min-width: 140px;
}

/* 操作按钮区域样式 */
.operation-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
}

.btn-status, .btn-delete, .btn-view {
  padding: 6px 12px;
  border: none;
  font-size: 14px;
  height: 36px;
}

.btn-status { 
  background-color: #faad14; 
  color: white; 
}

.btn-status:hover { 
  background-color: #ffc53d;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(250, 173, 20, 0.3);
}

.btn-delete { 
  background-color: #ff4d4f; 
  color: white; 
}

.btn-delete:hover { 
  background-color: #ff7875;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
}

.btn-view { 
  background-color: #1890ff; 
  color: white; 
}

.btn-view:hover { 
  background-color: #40a9ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

/* 无数据提示样式 */
.no-data {
  text-align: center;
  color: #8c8c8c;
  padding: 40px 0;
  border: 1px solid #f5f5f5;
  border-top: none;
  font-size: 16px;
  background-color: #fafafa;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(2px);
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.dialog {
  background: white;
  border-radius: 10px;
  width: 540px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.1);
  animation: slideIn 0.3s;
}

@keyframes slideIn {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f5f5f5;
}

.dialog-header h3 {
  font-size: 18px;
  margin: 0;
  color: #1f2329;
}

.dialog-close {
  font-size: 20px;
  background: none;
  border: none;
  cursor: pointer;
  color: #8c8c8c;
  transition: all 0.3s;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-close:hover {
  color: #1f2329;
  background-color: #f5f5f5;
}

.dialog-content {
  padding: 20px;
}

.form-group {
  margin-bottom: 18px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  font-size: 15px;
}

.form-group input, .form-group select, .form-group textarea {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;
  transition: all 0.3s;
  font-size: 15px;
}

.form-group input:focus, 
.form-group select:focus, 
.form-group textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.dialog-footer {
  padding: 14px 20px;
  border-top: 1px solid #f5f5f5;
  text-align: right;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 12px 0;
  border-top: 1px solid #f5f5f5;
  flex-wrap: wrap;
  gap: 16px;
}

.pagination-info {
  color: #666;
  font-size: 15px;
}

.pagination {
  display: flex;
  gap: 8px;
}

.pagination-btn {
  border: 1px solid #d9d9d9;
  background: white;
  padding: 6px 12px;
  font-size: 14px;
  height: 36px;
  min-width: 36px;
}

.pagination-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #f0f7ff;
}

.pagination-btn.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.pagination-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
  background-color: #f5f5f5;
}

/* 状态标签样式 */
.status-tag {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
}

.status-active {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-inactive {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .module-card {
    padding: 16px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .search-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .operation-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .data-table th:nth-child(8),
  .data-table td:nth-child(8) {
    min-width: auto;
  }
  
  .pagination-container {
    flex-direction: column;
    align-items: center;
  }
}

</style>